<template>
  <div class="club-details">
    <div class="info-sections">
      <!-- 社长信息展示区 -->
      <el-card class="section leader-info-card" shadow="hover">
        <p class="leader-name">社长: {{ clubDetails?.userVO.userName }}</p>
        <p>专业: {{ clubDetails?.userVO.major || "未填写" }}</p>
        <p>账号: {{ clubDetails?.userVO.userAccount }}</p>
        <p>联系方式: {{ clubDetails?.userVO.phoneNumber || "未填写" }}</p>
      </el-card>
      <!-- 社团公告展示区 -->
      <el-card class="section announcement-info-card" shadow="hover">
        <h3 class="activity-title" v-if="clubDetails?.clubAnnouncementVo.title">
          {{ clubDetails?.clubAnnouncementVo.title }}
        </h3>
        <p v-else class="activity-title">暂无公告</p>

        <p v-if="clubDetails?.clubAnnouncementVo.content">
          {{ clubDetails?.clubAnnouncementVo.content }}
        </p>
        <div class="actions">
          <el-button
            type="primary"
            size="small"
            v-if="clubDetails?.clubAnnouncementVo.title"
            @click="announcementDetail"
            >公告详情</el-button
          >
        </div>
      </el-card>
      <!-- 社团活动展示区 -->
      <el-card class="section activity-info-card" shadow="hover">
        <h3 class="activity-title" v-if="recentActivity?.activityTitle">
          {{ recentActivity?.activityTitle }}
        </h3>
        <p v-else class="activity-title">暂无活动</p>

        <div v-if="recentActivity?.status" class="activity-status">
          <span>活动状态: </span>
          <el-tag>{{ recentActivity?.status }}</el-tag>
        </div>

        <p v-if="recentActivity?.activityContent">
          {{ recentActivity?.activityContent }}
        </p>
        <div class="actions">
          <el-button
            type="primary"
            size="small"
            v-if="recentActivity?.activityTitle"
            @click="activityDetail"
            >活动详情</el-button
          >
        </div>
      </el-card>
    </div>
    <div class="club-view-action-bar" v-if="isShowActionBar">
      <el-button
        v-if="!isMember"
        type="primary"
        size="default"
        @click="joinClub"
        >加入社团</el-button
      >
      <el-button v-else type="danger" size="default" @click="leaveClub"
        >退出社团</el-button
      >
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  ActivityControllerService,
  type ActivityQueryRequest,
  ClubControllerService,
  type ClubMemberQueryRequest,
} from "../../../../../generated";
import { ElMessage } from "element-plus";
import { useUserStore } from "../../../../stores/user.ts";
import USER_ROLE_ENUM from "../../../../access/userRoleEnum.ts";

const route = useRoute();

interface Club {
  id: number;
  clubName: string;
  userVO: {
    userName: string;
    userAccount: string;
    phoneNumber: string | null;
    major: string | null;
    grade: string | null;
  };
  tags: string[];
  introduction: string;
  memberCount: number;
  clubAnnouncementVo: {
    id: number;
    title: string;
    content: string;
    createTime: string;
    isDelete: string;
  };
}

interface ShowedActivity {
  id: number;
  activityTitle: string;
  activityContent: string;
  status: string;
}

const clubId = Number(route.query.clubId);
const userStore = useUserStore();

const isMember = ref(false);
const isShowActionBar = ref(true);
const clubDetails = ref<Club | null>(null);
const recentActivity = ref<ShowedActivity | null>(null);

const loadClubDetails = async (clubId: number) => {
  try {
    const response = await ClubControllerService.getClubVoById(clubId);
    if (response.code === 0 && response.data) {
      clubDetails.value = response.data; // 存储社团详情数据
    } else {
      clubDetails.value = null; // 如果数据为空或格式不正确，设置为 null
      console.error(
        "加载社团详情失败:",
        response.message || "返回数据格式错误",
      );
    }

    const activityQueryRequest = {
      clubId: clubId,
    } as ActivityQueryRequest;
    const activitiesResponse =
      await ActivityControllerService.listActivityVoByPage(
        activityQueryRequest,
      );
    if (activitiesResponse.code === 0) {
      recentActivity.value = activitiesResponse.data?.records[0];
    } else {
      clubDetails.value = null; // 如果数据为空或格式不正确，设置为 null
      ElMessage.error("加载活动详情失败:" + activitiesResponse.message);
    }
  } catch (error) {
    clubDetails.value = null; // 如果接口调用失败，设置为 null
    console.error("加载社团详情时发生错误:", error.message || error);
  }
};

const checkMembershipStatus = async () => {
  if (userStore.userRole === USER_ROLE_ENUM.ADMIN) {
    isMember.value = true;
    isShowActionBar.value = false;
    return;
  } else if (
    userStore.userRole === USER_ROLE_ENUM.MANAGER &&
    userStore.managedClubId === clubId
  ) {
    isMember.value = true;
    isShowActionBar.value = false;
    return;
  }

  try {
    const response = await ClubControllerService.isMemberOfClub({
      clubId: clubId,
      userId: userStore.id,
    } as ClubMemberQueryRequest);

    if (response.code === 0) {
      isMember.value = response.data;
    } else {
      ElMessage.error("无法检查身份状态");
    }
  } catch (error) {
    console.error("检查会员状态时发生错误:", error);
    ElMessage.error("无法检查身份状态");
  }
};

onMounted(async () => {
  await loadClubDetails(clubId);
  await checkMembershipStatus();
});

const joinClub = () => {
  const url = `/application/add/join-club?clubId=${clubId}`;
  window.open(url, "_blank");
};

const leaveClub = () => {
  const url = `/application/add/quit-club?clubId=${clubId}`;
  window.open(url, "_blank");
};

const router = useRouter();
const announcementDetail = () => {
  router.push({
    path: "/club/announcement/info",
    query: { id: clubDetails.value?.clubAnnouncementVo.id, clubId: clubId },
  });
};

const activityDetail = () => {
  router.push({
    path: "/activity/details",
    query: { activityId: recentActivity.value?.id, clubId: clubId },
  });
}
</script>

<style scoped>
.info-sections {
  display: flex;
  gap: 20px;
  flex: 2;
  margin-top: 10px;
  padding-bottom: 40px; /* 为按钮留出空间 */
}

.section {
  flex: 1;
  padding: 20px;
  border-radius: 8px;
  position: relative;
}

p {
  color: #3f51b5;
}

.actions {
  position: absolute;
  bottom: 10px;
  right: 10px;
  display: flex;
  gap: 10px;
}
.leader-name {
  font-size: 20px;
  font-weight: bold;
}

.announcement-title,
.activity-title {
  font-size: 18px;
  font-weight: bold;
  text-transform: uppercase;
  color: #5c6bc0;
}

.club-view-action-bar {
  display: flex;
  justify-content: flex-end;
}
</style>
